import { createContext, useState, useContext, ReactNode } from 'react';
import { ToastContextType, Toast, ToastType } from './types';
import { ToastContainer } from './ToastContainer';

// 创建上下文
const ToastContext = createContext<ToastContextType | undefined>(undefined);

// Toast提供者组件
export const ToastProvider = ({ children }: { children: ReactNode }) => {
  const [toasts, setToasts] = useState<Toast[]>([]);

  // 添加一个Toast
  const addToast = (type: ToastType, title: string, message: string, duration?: number) => {
    const id = `toast-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
    const newToast: Toast = {
      id,
      type,
      title,
      message,
      duration,
      createdAt: Date.now()
    };

    // 使用自定义事件添加Toast，这样可以确保即使在非React上下文中也能添加Toast
    const event = new CustomEvent('addToast', { detail: newToast });
    window.dispatchEvent(event);

    // 同时更新state
    setToasts(prevToasts => [...prevToasts, newToast]);

    return id;
  };

  // 移除一个Toast
  const removeToast = (id: string) => {
    setToasts(prevToasts => prevToasts.filter(toast => toast.id !== id));
  };

  return (
    <ToastContext.Provider value={{ toasts, addToast, removeToast }}>
      {children}
      <ToastContainer />
    </ToastContext.Provider>
  );
};

// 自定义Hook，用于在组件中使用Toast
export const useToast = () => {
  const context = useContext(ToastContext);
  
  if (context === undefined) {
    throw new Error('useToast must be used within a ToastProvider');
  }
  
  return {
    // 成功消息
    success: (title: string, message: string, duration?: number) => 
      context.addToast('success', title, message, duration),
    
    // 错误消息
    error: (title: string, message: string, duration?: number) => 
      context.addToast('error', title, message, duration),
    
    // 信息消息
    info: (title: string, message: string, duration?: number) => 
      context.addToast('info', title, message, duration),
    
    // 警告消息
    warning: (title: string, message: string, duration?: number) => 
      context.addToast('warning', title, message, duration),
      
    // 原始添加方法
    addToast: context.addToast,
    
    // 移除方法
    removeToast: context.removeToast
  };
}; 